
const fs = require('fs-extra')
const inquirer = require('inquirer')
const shell = require('shelljs')
const loading = require('ora')()
const print = require('../../lib/print')
const utils = require('../../lib/utils')

/*
 * 配置文件格式：{codePath: '', businessLines: [], devBranch: []}  
 * - codePath: 代码仓库地址
 * - businessLines: 开发的业务线
 * - devBranch: 开发的分支
 */                
let _configInfo = utils.readConfigFile('checkout_branch.config.json', {codePath: '', businessLines: [], devBranch: []})

module.exports = async function () {
    try {
        checkConfigFile()
        let branch = await chooseBranch()
        for (const index in _configInfo.businessLines) {
            const element = _configInfo.businessLines[index];
            checkoutBranch(branch, element)
        }
        // 切换完分支后，需要执行 Pod install 
        await podCommand() 
        // 直接打开项目
        shell.exec('open XYMainApp.xcworkspace')
    } catch (error) {
        print.errorLog(error)
    }
}

/*
 * 校验配置文件内容
 */
function checkConfigFile() {
    if (!fs.existsSync(_configInfo.codePath)) { 
        throw 'codePath 不能为空'
        return
    }
    if (!_configInfo.businessLines) {
        throw 'businessLines 不能为空'
        return
    }
    if (!_configInfo.devBranch) {
        throw 'devBranch 不能为空'
        return
    }
    print.successLog('已读取本地配置')
}

/*
 * 选择开发的分支
 */
function chooseBranch() {
    const promptList = [
        {
            type: "list",
            message: "请选择切换的开发分支：",
            name: "branch",
            choices: _configInfo.devBranch,

        }
    ]
    return new Promise((resolve, reject) => {
        inquirer.prompt(promptList)
            .then(answer => {
                resolve(answer.branch)
            })
    })
}

/*
 * 列举业务线所有分支，匹配到待切换的分支则进行切换
 */
function checkoutBranch(branch, business) {
    shell.cd(`${_configInfo.codePath}/${business}`)
    // 列举当前业务线的所有分支
    let result = shell.exec('git branch', {silent: true})
    if (result.toString().indexOf(branch) !== -1) { // 包含待切换的分支
        shell.exec(`git checkout ${branch}`, {silent: true})
        print.successLog(`${business} 已切换到 ${branch}`)
    }else {  //不包含时就需要切换到 master 分支
        shell.exec('git checkout master', {silent: true})
        print.successLog(`${business} 已切换到 master`)
    }
}

/*
 * 主工程下执行 Pod install 
 */
function podCommand() {
    return new Promise((resolve, reject) => {
        let XYMainAppPath = `${_configInfo.codePath}/XYMainApp`
        shell.cd(XYMainAppPath)

        loading.start('pod install...')
        utils.asyncExecShell('pod install')
            .then(res => {
                loading.stop()
                console.log(res)
                resolve()
            })
            .catch(err => {
                loading.stop()
                reject(err)
            })
    })
}
